package com.service.uai.engine.comm;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.bpms.common.CommonUtil;
import com.bpms.common.Param;
import com.bpms.eai.ISyncComm;

public class HDPrintClient implements ISyncComm {

	public byte[] sendBuffer(byte[] buffer) {
		Socket st = null;
		OutputStream outputStream = null;
		int port = Integer
		.parseInt(Param.getValue("UAI", "atm_send_port"));
		String ip=Param.getValue("UAI", "atm_send_ip");
		int timeout =Integer.parseInt(Param.getValue("UAI", "atm_send_timeout"));
		try{
			CommonUtil.debug("HDPrintClient.ip:"+ip+":"+port);
			
			st = new  Socket(ip,port);
			st.setSoTimeout(timeout*1000);
			
			CommonUtil.debug("HDPrintClient.sendBuf("+new String(buffer).length()+")"+new String(buffer));
			
//			开始发送


			outputStream = st.getOutputStream();
			OutputStream dataOutputStream = new DataOutputStream(
					new BufferedOutputStream(outputStream));
//			OutputStream dataOutputStream = new DataOutputStream(outputStream);
//					new BufferedOutputStream());
			//delphi发送规则

//			int buffsize = myByte.toInteger(buffer);
//			byte[] buff=myByte.byteCon(myByte.toBytes(buffsize), buffer);
			
			dataOutputStream.write(buffer);
			dataOutputStream.flush();
//			
//			byte[] head=new byte[4];
//			int headlen=st.getInputStream().read(head, 0, 4);
//			if(headlen<4)
//			{
//				CommonUtil.debug("the send head is short "+new String(head));
//				return null;
//			}
//			CommonUtil.debug("receive package head is ："+new String(head));
			byte[] head=new byte[8];
			int headlen = st.getInputStream().read(head, 0, 8);
			if(headlen<4){
				CommonUtil.debug("the send head is short "+new String(head));
				return null;
			}
			
			int length = Integer.parseInt(new String(head));
			byte[] body=new byte[length];
			int len=st.getInputStream().read(body, 0, length);
			if(len<length)
			{
				CommonUtil.debug("HDPrintClient the send body is short "+new String(body));
				return null;
			}

			CommonUtil.debug("HDPrintClient receive package body is ："+new String(body));
			return body;
			
		}catch(Exception e){
			CommonUtil.debug("HDPrintClient.sendBuffer exception",e);
			return null;
		}
		
	}

}
